package com.universityJob.modules.data.controller;

import com.universityJob.common.annotation.SysLog;
import com.universityJob.common.utils.ExportExcel;
import com.universityJob.common.utils.FileUtil;
import com.universityJob.common.utils.PageUtils;
import com.universityJob.common.utils.R;
import com.universityJob.modules.data.entity.DataHistoryEntity;
import com.universityJob.modules.data.service.DataHistoryService;
import com.universityJob.modules.sys.controller.AbstractController;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author mao on 2021/5/13.
 * @version 1.0 maozhijob@163.com
 */
@RestController
@RequestMapping("data/history")
public class DataHistoryController extends AbstractController {
    @Autowired
    private DataHistoryService dataHistoryService;

    /**
     * 存储请求产生的文件名
     */
    Map<String, String> fileInfo = new HashMap<>();
    @Value("${upload.file}excel/")
    String excelPath;
    private Logger logger = LoggerFactory.getLogger(getClass());
    /**
     * 所有历史数据列表
     */
    @GetMapping("/list")
    @RequiresPermissions("sys:history:list")
    public R list(@RequestParam Map<String, Object> params){

        R r = dataHistoryService.queryPage(params);

        return r;
    }
    /**
     * 推送数据历史
     * 可视化
     */
    @GetMapping("/recommend")
    public R recommend(@RequestParam Map<String, Object> params){
        R r = dataHistoryService.selectRecommends(params);
        return r;
    }
    /**
     * 统计职位数据分布
     * 可视化
     */
    @GetMapping("/statisticsJob")
    public R statisticsJob(){
        R r = dataHistoryService.statisticsJob();
        return r;
    }
    /**
     * 历史数据信息
     */
    @GetMapping("/info/{historyId}")
    @RequiresPermissions("sys:history:info")
    public R info(@PathVariable("historyId") Long historyId){
        DataHistoryEntity history = dataHistoryService.findByid(historyId);
        return R.ok().put("history", history);
    }

    /**
     * 保存历史数据
     */
    @SysLog("保存历史数据")
    @PostMapping("/save")
    @RequiresPermissions("sys:history:save")
    public R save(@RequestBody DataHistoryEntity history){

        R r = dataHistoryService.saveHistory(history);

        return r;
    }

    /**
     * 修改历史数据
     */
    @SysLog("修改历史数据")
    @PostMapping("/update")
    @RequiresPermissions("sys:history:update")
    public R update(@RequestBody DataHistoryEntity history){

        R r = dataHistoryService.update(history);

        return r;
    }

    /**
     * 删除历史数据
     */
    @SysLog("删除历史数据")
    @PostMapping("/delete")
    @RequiresPermissions("sys:history:delete")
    public R delete(@RequestBody Long[] historyIds){
        R r = dataHistoryService.deleteBatch(historyIds);

        return r;
    }
    /**
     * 导入数据
     */
    @PostMapping("/inputExcel")
    @RequiresPermissions("sys:history:save")
    public R inputExcel(HttpServletResponse response, @RequestBody Map<String, Object> params) throws Exception {
        //向前端返回的数据
        Map<String, Object> data = new HashMap<>();
        String uid = UUID.randomUUID().toString().replaceAll("-", "");
        this.fileInfo.put(uid, "-1");
        data.put("uid", uid);
        data.put("fileName","");
        params.put("uid", uid);
        logger.info("开始导入数据");
        Thread thread = new Thread(() -> {
            try {
                int i = dataHistoryService.inputExcel(response, params);
                this.fileInfo.put(uid, String.valueOf(i));
                logger.info("数据导入成功！");
            } catch (Exception e) {
                logger.error("数据导入出错！");
            }
        });
        thread.start();

        return R.ok(data);
    }
    /**
     * 导出excel
     */
    @PostMapping("/exportExcel")
    @RequiresPermissions("sys:history:save")
    public R exportExcel(HttpServletResponse response, @RequestBody Map<String, Object> params) throws Exception {
        //向前端返回的数据
        Map<String, Object> data = new HashMap<>();
        String uid = UUID.randomUUID().toString().replaceAll("-", "");
        this.fileInfo.put(uid, "0");
        data.put("uid", uid);
        data.put("fileName", params.get("fileName"));
        params.put("path", excelPath);
        params.put("uid", uid);
        logger.info("开始准备Excel文件：{}",params.get("fileName"));
        Thread thread = new Thread(() -> {
            try {
                int i = dataHistoryService.exportStatisticsReport(response, params);
                this.fileInfo.put(uid, String.valueOf(i));
                logger.info("文件已经准备好，准备开始下载！");
            } catch (Exception e) {
                logger.error("文件导出出错！");
            }
        });
        thread.start();

        return R.ok(data);
    }
    /**
     * 循环请求接口
     */
    @PostMapping("/testpolling")
    @ResponseBody
    public R testPolling(@RequestBody Map<String, Object> param) {
        String uid = ExportExcel.nvll(param.get("uid"));
        String fileName = ExportExcel.nvll(param.get("fileName"));
        Map<String, Object> pollingData = new HashMap<>();
        pollingData.put(uid, fileInfo.get(uid));
        pollingData.put("fileName", fileName);
        return R.ok(pollingData);
    }
    /**
     * 最后下载的接口
     */
    @RequestMapping("/testdownload")
    @ResponseBody
    public void testDownload(HttpServletResponse response, @RequestParam Map<String, Object> param) {
        String fileName = (String) param.get("fileName");
        String uid = ExportExcel.nvll(param.get("uid"));
        String uidFolder = excelPath + uid;
        try {
            InputStream bis = new BufferedInputStream(new FileInputStream(new File(uidFolder + "/" + fileName)));
            fileName = URLEncoder.encode(fileName, "UTF-8");
            // 设置文件下载头
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
            // 1.设置文件ContentType类型，这样设置，会自动判断下载文件类型
            response.setContentType("multipart/form-data;charset=utf-8");
            BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
            int len = 0;
            byte[] buf = new byte[2048];
            while ((len = bis.read(buf)) != -1) {
                out.write(buf, 0, len);
            }
            bis.close();
            out.close();
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //删除临时文件和文件信息
            FileUtil.deleteDirectory(uidFolder);
            fileInfo.remove(uid);
        }
    }
}
